package com.wxy.controller;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wxy.domain.User;
import com.wxy.domain.jwtUser;
import com.wxy.domain.myException;
import com.wxy.service.jwtServiceConfig;
import com.wxy.service.jwtServiceImpl;
import com.wxy.service.userService;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/boot3")
public class loginController {
	@Autowired
	private jwtServiceImpl jwtServiceImpl;
	@PostMapping("/login")
	//@ResponseBody
	public String login(HttpServletRequest request,HttpServletResponse response) {
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			jwtUser user=new jwtUser(username, password);
			User user2=jwtServiceImpl.findUser(user);
			if(user2==null)
				throw new myException("登录失败，账号或密码错误..");
			String token=jwtServiceConfig.getToken(user2.getId());
			if(token==null)
				throw new myException("非法账号密码!!!");
			Cookie cookie=new Cookie("token",token);
			response.addCookie(cookie);
			return "success";
	}
	@GetMapping("/getMessage")
	@ResponseBody
	public User getMessage(HttpServletRequest request,HttpServletResponse response) {
//		Cookie[] cookies=request.getCookies();
//		if(cookies==null)
//			throw new myException("请先登录...");
//		String tokenString="";
//		for (Cookie cookie : cookies) {
//			if(cookie.getName().equals("token")) {
//				tokenString=cookie.getValue();
//				break;
//			}
//		}
//		Map<String,Object> map=jwtServiceConfig.checkToken(tokenString);
		Map<String,Object> map=(Map<String, Object>) request.getAttribute("body");
		int id=(int) map.get("userId");
		User user=jwtServiceImpl.findById(id);
		if(user==null)
			throw new myException("伪造登录...");
		return user;
 	}
}
